﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Sql;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Common.Logging;
using Newtonsoft.Json;
using Quartz;
using In.Api.Dto.Notify;
using In.Api.Dto.Notify.Notification;
using InDbContext;
using Rmq.Center;
using Oracle.DataAccess.Client;

namespace In.TaskRunner.QuartzJobs
{
    public class CommonNoticeJob: IJob
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(CommonNoticeJob));

        public void Execute(IJobExecutionContext context)
        {
            Logger.InfoFormat("Executing job: {0}", context.JobDetail.Key);

            var connstr = ConfigurationManager.ConnectionStrings["HISNoticeEntity"].ConnectionString;
            var connection = new OracleConnection(connstr);
            try
            {
                connection.Open();
            }
            catch (Exception ex)
            {
                Console.WriteLine(JsonConvert.SerializeObject(ex));
                Logger.ErrorFormat("CommonNoticeJob OracleConnection出错：{0}", ex.Message);
                throw;
            }

            //is_read 0,未读，1,已读
            string sql = "select rowid,NoticeType,PatientId,NoticeTime,AppNo,ClinicNo,dept_name,doct_name from CommonNotice where RowNum < 50 and is_read = '0'";
            var adapter = new OracleDataAdapter(sql, connection);
            try
            {
                DataTable dt = new DataTable();
                adapter.Fill(dt);

                if (dt.Rows.Count > 0)
                {
                    Console.WriteLine("找到{0}条一般通知", dt.Rows.Count);
                }

                using (var ctx = new HospDatabaseEntity())
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        var rowId = dr["RowId"].ToString();
                        //oracle中间库的PatientId字段实际是CardNo数据
                        var cardNo = dr["PatientId"].ToString();
                        var patient = ctx.HospCards.FirstOrDefault(card => card.CardNo == cardNo);
                        if (patient != null)
                        {
                            var commonNotice = new In.Api.Dto.Notify.Notification.CommonNotice();
                            commonNotice.NoticeType = dr["NoticeType"].ToInt32();
                            commonNotice.PatientId = patient.PatientId;
                            commonNotice.Name = patient.Name;
                            commonNotice.CardNo = patient.CardNo;
                            commonNotice.NoticeTime = dr["NoticeTime"].ToDateTime();
                            commonNotice.AppNo = dr["AppNo"].ToString();
                            commonNotice.ClinicNo = dr["ClinicNo"].ToString();
                            commonNotice.DeptName = dr["dept_name"].ToString();
                            commonNotice.DoctorName = dr["doct_name"].ToString();

                            ProcessNotice(commonNotice);
                        }

                        SetNoticeIsRead(rowId);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(JsonConvert.SerializeObject(ex));
                Logger.ErrorFormat("CommonNoticeJob出错：{0}", ex.Message);
            }
            adapter.Dispose();
            connection.Close();
            connection.Dispose();
        }

        private void ProcessNotice(In.Api.Dto.Notify.Notification.CommonNotice commonNotice)
        {
             var notification = new NotificationRequest()
            {
                NotificationType = "CommonNotice",
                NotificationInfo = JsonConvert.SerializeObject(commonNotice)
            };
            Console.WriteLine("一般通知:{0}", notification.NotificationInfo);

            try
            {
                var hospMessageProducer = new HospMessageProducer();
                hospMessageProducer.Publish(new HospMessageMsg()
                {
                    NotificationType = notification.NotificationType,
                    NotificationInfo = notification.NotificationInfo
                });

                var alipayApiAddress = ConfigurationManager.AppSettings["AlipayNotificationApiBaseAddress"];
                HttpClient.PostAsJsonAsync(alipayApiAddress, notification);
            }
            catch (Exception e)
            {
                Logger.ErrorFormat("发送一般通知出错：{0}", e.Message);
               
            } 
        }

        private static readonly HttpClient HttpClient = new HttpClient();

        private void SetNoticeIsRead(string rowId)
        {
            var connstr = ConfigurationManager.ConnectionStrings["HISNoticeEntity"].ConnectionString;
            var connection = new OracleConnection(connstr);
            connection.Open();
            string sql = string.Format("update CommonNotice set is_read = '1' where RowId = :rId");
            var cmd = new OracleCommand(sql, connection);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add(new OracleParameter(":rId", rowId));
            cmd.ExecuteNonQuery();
            connection.Close();
            connection.Dispose();
            //Notify(ServiceStatus.BUSY, "已读取一条一般通知" + rowId);
        }
    }
}
